import { message } from 'antd';
import axios from 'axios';
import store from 'store2';

/**
 * Types
 */
import type { AxiosError, AxiosResponse } from 'axios';

/**
 * Axios
 */
axios.defaults.baseURL = import.meta.env.VITE_API_URL;

axios.interceptors.request.use((config) => {
    if (store.has('token')) {
        config.headers.Token = store.get('token');
    }

    return config;
});

axios.interceptors.response.use(
    (response: AxiosResponse) => {
        // 用户未登录
        if (response.data.code === 11101) {
            message.error('用户未登录');
            store.remove('token');
            store.remove('user');
            location.href = '/#/login';
        }

        // 令牌已过期
        if ([11105, 11108].includes(response.data.code)) {
            message.error('令牌已过期');
            store.remove('token');
            store.remove('user');
            location.href = '/#/login';
        }

        return response;
    },
    (error: AxiosError) => {
        message.error(error.message);

        return Promise.reject(error);
    },
);

export default axios;
